package com.newer.textdbnotepad

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.newer.textdbnotepad.sdk.NoteDetail
import com.newer.textdbnotepad.sdk.NoteRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class NoteDetailViewModel @Inject constructor(private val noteRepository: NoteRepository) : ViewModel() {

    private val _noteDetail = MutableLiveData<NoteDetail>()
    val noteDetail: LiveData<NoteDetail> = _noteDetail

    private val _shareFlow = MutableSharedFlow<String>()
    val shareFlow: Flow<String> = _shareFlow

    fun getNote(noteKey: String) {
        viewModelScope.launch {
            _noteDetail.value = noteRepository.getNote(noteKey) ?: NoteDetail(noteKey = noteKey, noteTitle = "", noteContent = "")
        }
    }

    fun save(title: String, content: String) {
        viewModelScope.launch {
            val noteDetail = _noteDetail.value?.copy(noteTitle = title, noteContent = content) ?: return@launch
            noteRepository.updateNote(noteDetail)
            _shareFlow.emit("保存成功")
        }
    }
}